#coding:utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

import os

from flask import Flask,render_template,request,redirect,session,jsonify
app = Flask(__name__)
app.secret_key='2EsDrsG3qeLWsrXHtLmRRj4P'


from modules import users,monitor,message,ssh,confs
import json
import time

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/user/login',methods=['POST','GET'])
def login():
    result = {}
    if request.method == 'POST':
        user_info = request.form.to_dict()
        u = users.Users()
        result = u.login(user_info=user_info)
        #return str(result)
        if result.get('code') == 0:
            session['phone'] = user_info['phone']
            session['username'] = result['username']
            return redirect('/')
    return render_template('login.html',result=result)

@app.route('/user/logout')
def logout():
    del session['phone']
    del session['username']
    return redirect('/')

@app.route('/user/register',methods=['POST','GET'])
def register():
    result = {}
    if request.method == 'POST':
        user_info = request.form.to_dict()
        u = users.Users()
        result = u.register(user_info=user_info)
    return render_template('register.html',result=result)

@app.route('/user/password/forgot',methods=['POST','GET'])
def forget():
    result = {}
    if request.method == 'POST':
        user_info = request.form.to_dict()
        u = users.Users()
        result = u.register(user_info=user_info)
    return render_template('forgot.html',result=result)

@app.route('/monitor/views')
def views_monitor():
    result = {}
    m = monitor.SaveDb()
    result = m.get_all_monitor()
    return render_template('monitors.html',result=result,time=time, round=round)

@app.route('/admin')
def admin():
    result = {}
    return render_template('admin.html',result=result)

@app.route('/apis/monitor',methods=['POST','GET'])
@app.route('/apis/monitor/<hostname>',methods=['POST','GET'])
def apis_monitor(hostname=None):
    if not hostname:#如果不是查API
        if request.method == 'POST':#存储信息
            #check token
            #post info
            host_info = request.form.to_dict() #把客户端的参数转成字典
            try:
                data = json.loads(host_info.get('data'))
                if 'hostname' in data: #判断主机名是否提供
                    key = data.get('hostname')
                else:
                    return jsonify({'code' : 200, 'message': 'args not hostname'})
                value = json.dumps(data) #写到数据库
                s = monitor.SaveDb()
                ret = s.monitor(key,value)
                if ret.get('code',200) == 0:
                    return jsonify({'code' : 0, 'message' : 'success'})
                else:
                    return jsonify(ret)
            except Exception as e:
                raise e
        else:
            return jsonify({ 'code' : 201, 'message' : 'please you use POST method'})
    else: #查询数据
        s = monitor.SaveDb()
        ret = s.get_monitor(key=hostname)
        if ret.get('code',201) == 0:
            return jsonify({'code' : 0, 'message' : 'success', 'data' : ret})
        else:
            return jsonify(ret)

@app.route('/tools/class_notify',methods=['POST','GET']) 
def class_notify():
    result = {}
    if request.method == 'POST':
        mes = request.form.to_dict()
        m = message.Message()
        cls_type = mes['cls_type']; num = mes['num']
        time = mes['time'];  cls_content = mes['cls_content']

        if cls_type and num and time and cls_content:
            result = m.noity(cls_type=cls_type, num=num, 
                             cls_content=cls_content, time=time)
        else:
            result = {'code': 410, 'message' : '提供参数不全'} 
    return render_template('class_notify.html', result=result)  

@app.route('/tools/send_message',methods=['POST','GET'])  
def send_message():
    result = {}
    if request.method == 'POST':
        mes = request.form.to_dict()
        m = message.Message()
        phone = mes['phone']; content = mes['content']
        if phone and content:
            result = m.send(phone, content)
        else:
            result = {'code': 410, 'message' : '提供参数不全'}     
    return render_template('send_message.html', result=result) 

@app.route('/tools/run', methods=['POST','GET'])
def run():
    result = {}
    s = ssh.SSH()
    hosts = s.view_hosts()
    if request.method == 'POST':
        runs = request.form.to_dict()
        if 'host' and 'command' in runs:
            if runs['host']:
                host_info = s.get_hosts(runs['host'])
                if host_info.get('code',1) != 0:
                    result = host_info
                else:
                    host_info = host_info['host']
                    result = s.execute(command=runs['command'], host_info=host_info)
            else:
                result = {'code': 411, 'message' : '参数不能为空'}
        else:
            result = {'code': 410, 'message' : '提供参数不全'}

    return render_template('run.html', result=result, hosts=hosts)

@app.route('/tools/mult_run', methods=['POST','GET'])
def mult_run():
    result = {}
    if request.method == 'POST':
        mult_runs = request.form.to_dict()
        if mult_runs.get('command',''):
            s = ssh.SSH()
            result = s.mult_execute(mult_runs['command'])
        else:
            result = { 'code' : 402, 'message' : '参数不能为空'}
    return render_template('mult_run.html', result=result)

@app.route('/tools/mult_upload', methods=['POST','GET'])
def mult_upload():
    result = {}
    if request.method == 'POST':
        file = request.files['file']
        filename = file.filename
        path = os.path.join(confs.upath,filename)
        file.save(path)
        s = ssh.SSH()
        rpath = confs.rupath + filename
        result = s.mult_upload(lpath=path, rpath=rpath)
    return render_template('mult_upload.html', result=result)

if __name__ == '__main__':
    app.run(host='0.0.0.0dd',port=80,debug=True)